﻿using System;
using System.Data;
using System.Runtime.InteropServices;
using Microsoft.JScript;

namespace GtsServer.Common
{
    public class ExportExcel
    {
        public static void DataTableToLocalExcel(System.Data.DataTable table, string strExcelFileName)
        {
            string tempPath = @"D:\";
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

            //            Excel.Workbook obj=new Excel.WorkbookClass();

            //            obj.SaveAs("c:\zn.xls",Excel.XlFileFormat.xlExcel9795,null,null,false,false,Excel.XlSaveAsAccessMode.xlNoChange,null,null,null,null);


            int rowIndex = 1;

            int colIndex = 0;

            excel.Application.Workbooks.Add(true);

            foreach (DataColumn col in table.Columns)
            {
                colIndex++;
                excel.Cells[1, colIndex] = col.ColumnName;
            }
            foreach (DataRow row in table.Rows)
            {
                rowIndex++;
                colIndex = 0;
                foreach (DataColumn col in table.Columns)
                {
                    colIndex++;
                    excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
                }
            }
            excel.Visible = false;
            //excel.Sheets[0] = "sss";
            excel.ActiveWorkbook.SaveAs(tempPath + strExcelFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel7, null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null);
            //wkbNew.SaveAs strBookName
            //excel.Save(strExcelFileName);
            excel.Quit();
            excel = null;
            GC.Collect();//垃圾回收
        }

    }
}
